package com.example.util;

import com.example.dao.AdminDAO;
import com.example.model.CardInfo;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

public class CardTableModel extends AbstractTableModel {

    AdminDAO  adminDAO = new AdminDAO();
    private final String[] columnNames = {"卡ID", "用户ID", "开户日期", "开户金额", "余额", "是否挂失"};
    private List<CardInfo> cards = adminDAO.getCardInfo();


    public CardTableModel(List<CardInfo> cards) {
        this.cards = cards;
    }

    @Override
    public int getRowCount() {
        return cards.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        CardInfo card = cards.get(rowIndex);
        return switch (columnIndex) {
            case 0 -> card.getCardId();
            case 1 -> card.getCustomerId();
            case 2 -> card.getOpenDate();
            case 3 -> card.getOpenMoney();
            case 4 -> card.getBalance();
            case 5 -> card.getIsReportLoss();
            default -> null;
        };
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        // 只有ID列不可编辑
        return columnIndex != 0;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        CardInfo card = cards.get(rowIndex);
        switch (columnIndex) {
            case 1 -> card.setCustomerId((Integer) aValue);
            case 2 -> card.setOpenDate(LocalDateTime.parse((String) aValue));
            case 3 -> card.setOpenMoney(new BigDecimal((String) aValue));
            case 4 -> card.setBalance(new BigDecimal((String) aValue));
            case 5 -> card.setIsReportLoss((String) aValue);
        }
        if(!adminDAO.updateCardInfo(card)){
           return;
        }else{
            fireTableCellUpdated(rowIndex, columnIndex);
        }
    }

}
